package com.by.gateway.discovery;

import com.by.rpc.util.KeyUtils;
import org.springframework.data.redis.core.RedisTemplate;
import com.by.rpc.dto.ServiceInstance;
import com.by.rpc.registry.RedisServiceRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// 添加日志
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 服务发现组件
 * 基于Redis实现服务发现功能
 */
@Component
public class ServiceDiscovery {
    
    // 添加日志记录器
    private static final Logger logger = LoggerFactory.getLogger(ServiceDiscovery.class);
    
    private final RedisServiceRegistry redisServiceRegistry;
    
    @Autowired
    public ServiceDiscovery(RedisTemplate<String, Object> redisTemplate) {
        this.redisServiceRegistry = new RedisServiceRegistry(redisTemplate);
    }
    
    /**
     * 根据服务名称发现服务实例
     * 
     * @param serviceName 服务名称
     * @param version 服务版本
     * @param group 服务分组
     * @return 服务实例列表
     */
    public List<ServiceInstance> getInstances(String serviceName, String version, String group) {
        logger.debug("Discovering instances for service: {}, version: {}, group: {}", serviceName, version, group);
        
        // 注意：当前RedisServiceRegistry只支持按服务名发现，忽略version和group参数
        String serviceKey = KeyUtils.buildServiceKey(serviceName, version, group);
        List<ServiceInstance> instances = redisServiceRegistry.discover(serviceKey);
        logger.debug("Discovered {} instances for service: {}", instances != null ? instances.size() : 0, serviceName);
        return instances;
    }
    
    /**
     * 根据服务名称获取一个可用的服务实例
     * 
     * @param serviceName 服务名称
     * @param version 服务版本
     * @param group 服务分组
     * @return 服务实例，如果找不到返回null
     */
    public ServiceInstance getOneInstance(String serviceName, String version, String group) {
        logger.debug("Getting one instance for service: {}, version: {}, group: {}", serviceName, version, group);
        
        List<ServiceInstance> instances = getInstances(serviceName, version, group);
        if (instances != null && !instances.isEmpty()) {
            // 简单的负载均衡策略：返回第一个实例
            ServiceInstance instance = instances.get(0);
            logger.debug("Selected instance: {}", instance);
            return instance;
        }
        
        logger.warn("No instances found for service: {}", serviceName);
        return null;
    }
}